import { showSuccess, showError } from '../../utils/util'
import request from '../../utils/request'

Component({
    properties: {
        post: {
            type: Object,
            value: {}
        }
    },

    methods: {
        onPostClick(e) {
            const post = e.currentTarget.dataset.post
            wx.navigateTo({
                url: `/pages/post-detail/post-detail?id=${post.id}`
            })
        },

        async onLike(e) {
            const post = e.currentTarget.dataset.post

            try {
                if (post.isLiked) {
                    await request.post(`/posts/${post.id}/unlike`)
                    this.triggerEvent('likeChange', {
                        postId: post.id,
                        isLiked: false,
                        likeCount: post.likeCount - 1
                    })
                    showSuccess('取消点赞')
                } else {
                    await request.post(`/posts/${post.id}/like`)
                    this.triggerEvent('likeChange', {
                        postId: post.id,
                        isLiked: true,
                        likeCount: post.likeCount + 1
                    })
                    showSuccess('点赞成功')
                }
            } catch (error) {
                showError('操作失败')
            }
        },

        async onApply(e) {
            const post = e.currentTarget.dataset.post

            try {
                const result = await request.post('/team/apply', {
                    postId: post.id,
                    message: '我想加入这个活动'
                })

                if (result.success) {
                    showSuccess('申请成功')
                } else {
                    showError('申请失败')
                }
            } catch (error) {
                showError('申请失败')
            }
        }
    }
})